from qiniu import Auth, BucketManager, put_data, etag, urlsafe_base64_encode
import time
import os.path
import uuid
#需要填写你的 Access Key 和 Secret Key
access_key = 'Tg9vbJMCK7eQ0eye7vEHcDG49bveyvWejJKoMVAq'
secret_key = 'sIqu-4SKloJujVhUlWXZpdzu56Dk3RuER6DiWf4T'
#构建鉴权对象
q = Auth(access_key, secret_key)
#要上传的空间
bucket_name = 'qmfile'
#上传到七牛后保存的文件名
#生成上传 Token，可以指定过期时间等
# 上传策略示例
# https://developer.qiniu.com/kodo/manual/1206/put-policy
policy = {
 # 'callbackUrl':'https://requestb.in/1c7q2d31',
 # 'callbackBody':'filename=$(fname)&filesize=$(fsize)'
 # 'persistentOps':'imageView2/1/w/200/h/200'
 }
#3600为token过期时间，秒为单位。3600等于一小时
token = ''
get_time = 0
def get_token(key):
    global get_time
    now_time = int(time.time())
    if(now_time - get_time >= 3600 or token.strip()==''):
        token = q.upload_token(bucket_name, key, 3600)
        get_time = now_time
    return token

def upload(filedata):
    #上传到七牛后保存的文件名
    key = uuid.uuid4().hex + os.path.splitext(filedata.filename)[1]
    #生成上传 Token，可以指定过期时间等
    token = get_token(key)
    info = put_data(token, key, filedata.read())
    return info

def delete_qiniu(key):
    #上传到七牛后保存的文件名
    bucket = BucketManager(q)
    ret, info = bucket.delete(bucket_name, key)
    return info
